from struct import pack, unpack
from Callable import *

class Package:

  def __init__(self, code, serial = 0, content = None):
    self.code    = code
    self.serial  = serial
    self.content = list()
    
    if content != None:
      self.content = content.split(' ') 

  # Creates a new Package instance from a given binary blob
  def from_binary(blob):
    decoded_blob = unpack('!hhH', blob[:6])
    content_length = decoded_blob[0] - 6
    
    if content_length > 194:
      content_length = 194

    encoding = '!hhH' + str(content_length) + 's'
    decoded_blob = unpack(encoding, blob)
      
    return Package(decoded_blob[1], decoded_blob[2], decoded_blob[3])
    
  # Creates a static method from from_binary()
  from_binary = Callable(from_binary)
    
  # Creates a binary blob of this package with the layout in network order:
  # POSITION  TYPE    SIZE  DESCRIPTION
  # 0 - 1     short   2     Message length
  # 2 - 3     short   2     Message code
  # 4 - 5     ushort  2     Serial number
  # 6 - 199   char    194   Message 
  def to_binary(self):
    content_length = len(' '.join(self.content))
    encoding = '!hhH' + str(content_length) + 's'          
    return pack(encoding, content_length + 6, self.code, self.serial, ' '.join(self.content))
    
  def add_word(self, word):
    self.content.append(word)

  def get_word(self, index):
    if index < len(self.content):
      return self.content[index]
    else:
      return False
  
  def get_text(self, index):
    if index < len(self.content):
      return ' '.join(self.content[index:])
    else:
      return False
     
